<template>
  <div style="height: 100%">
    <div class="searchBox">
      <form-box :fields="searchField" :is-filter="true" :submit-handle="searchHandle" />
    </div>

    <div class="baby-box">
      <div style="display: flex;">
        <el-button type="primary" @click="add">新增</el-button>
      </div>
      <Ltable
        v-if="list.length > 0 || loading"
        :data="list"
        :columns="config.memorandumColumns"
        class="mt16"
        :loading="loading"
      >
        <template #clssesName="{ row }">
          {{ getClassName(row.classesId) }}
        </template>
        <template #img="{ row }">
          <div v-if="row['childrenMemorandums'].length>=1&&row['childrenMemorandums'][0]['file']" style="display: flex;flex-direction: row;align-items: flex-end">
            <div v-for="(url, idx) in getFile(row['childrenMemorandums'])" :key="idx">
              <template v-if="idx<2">
                <el-image
                  :key="url"
                  style="width: 40px;height: 40px;border-radius: 4px;margin-right: 8px;"
                  :src="url"
                  lazy
                  :preview-src-list="getFile(row['childrenMemorandums'])"
                />
              </template>
            </div>
            <span v-if="getFile(row['childrenMemorandums']).length>2" style="font-weight: bold;">...</span>
          </div>
          <span v-else>-</span>
        </template>
        <template #content="{ row }">
          <span v-if="row['childrenMemorandums']&&row['childrenMemorandums'].length>=1">{{ row['childrenMemorandums'][0]['content'] }}</span>
          <span v-else>-</span>
        </template>
        <template #operate="{ row }">
          <el-button size="mini" type="text" class="yellow" @click="getDetails(row.id)">详情</el-button>
          <el-button size="mini" type="text" class="blue" @click="title = '新增备忘录'; addMemorandum(row)">添加</el-button>
          <el-popconfirm
            title="您确认对该数据进行删除操作吗?"
            class="ml10"
            @confirm="() => delChildrenMemorandum(row.id)"
            @onConfirm="() => delChildrenMemorandum(row.id)"
          >
            <el-button slot="reference" size="mini" type="text" class="red">删除</el-button>
          </el-popconfirm>
        </template>
      </Ltable>
      <div v-else class="quesheng">
        <img src="@/assets/quesheng.png" alt="">
        <span>暂无数据</span>
      </div>
      <div v-if="list.length > 0 && !loading" style="text-align: right;">
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <el-drawer
      :title="title"
      :visible.sync="drawer"
      :before-close="beforeClose"
      :destroy-on-close="true"
      custom-class="add-drawer"
      size="45%"
      :wrapper-closable="false"
    >
      <div v-loading="loadingFrom" style="padding: 0 30px">
        <from-page
          ref="fromRef"
          :label-width="null"
          :rules="config.rules"
          :from-config="memorandumFrom"
          :grid-data="gridData"
          :value="detail"
          @selectChange="selectChange"
          @submitForm="submitForm"
        />
      </div>
    </el-drawer>
    <el-drawer
      title="备忘详情"
      :visible.sync="show"
      :destroy-on-close="true"
      custom-class="add-drawer"
      size="680px"
      :wrapper-closable="false"
    >
      <div v-loading="loadingFrom" style="padding: 0 24px">
        <div class="memorandum-box">
          <div class="memorandum-box-item">
            <span>所在班级：</span>
            <span style="color: #666666 !important;">{{ getClassName(detail['classesId']) }}</span>
          </div>
          <div class="memorandum-box-item">
            <span>宝宝姓名：</span>
            <span style="color: #666666 !important;">{{ detail['name'] }}</span>
          </div>
        </div>
        <div class="memorandum-title">备忘内容</div>
        <div
          v-for="(item, idx) in detail['childrenMemorandums']"
          :key="idx"
          class="memorandum-box"
          :style="{ marginBottom: idx + 1 === detail['childrenMemorandums'].length ? '' : '16px' }"
        >
          <div class="memorandum-box-item" style="display: flex;align-items: center;justify-content: space-between;">
            <div>
              <span>创建人：</span>
              <span style="color: #666666 !important;">{{ detail['createUserName'] }}</span>
            </div>
            <div>
              <el-button
                size="mini"
                type="text"
                class="yellow"
                @click="title = '编辑备忘录'; addMemorandum({ ...detail, ...item })"
              >编辑</el-button>
              <el-popconfirm
                title="您确认对该数据进行删除操作吗?"
                class="ml10"
                @confirm="() => delMemorandum(item.id)"
                @onConfirm="() => delMemorandum(item.id)"
              >
                <el-button slot="reference" size="mini" type="text" class="red">删除</el-button>
              </el-popconfirm>
            </div>
          </div>
          <div class="memorandum-box-item">
            <span>创建时间：</span>
            <span style="color: #666666 !important;">{{ date.formatTimestamp(item['createTime']) }}</span>
          </div>
          <div class="memorandum-box-item">
            <div><span>备忘内容：</span>
              <span style="color: #666666 !important;">{{ item['content'] }}</span>
            </div>
            <div v-if="item['file']" class="mt16">
              <el-image
                v-for="(url) in item['file'].split(',')"
                :key="url"
                style="width: 56px;height: 56px;border-radius: 4px;margin-right: 8px;"
                :src="url"
                lazy
                :preview-src-list="item['file'].split(',')"
              />
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import * as config from '../config'
import FromPage from '@/components/Basic/FromPage/index'
import { mapGetters } from 'vuex'
import { getClassesByArea } from '@/api/common'
import request from '@/utils/request'
import { selChildrenMemorandumPage, details, delChildrenMemorandum, delMemorandum } from '../api'
import * as date from '@/utils/date'
import axios from 'axios'
export default {
  name: 'Manage',
  components: {
    FromPage
  },
  data () {
    return {
      title: '新增备忘',
      detail: {},
      date,
      gridData: {
        columns: 1, // 默认列数
        rows: 1, // 默认行数
        rowsWidth: '77px',
        columnsNumber: '20px',
        rowsNumber: '10px'
      },
      config,
      drawer: false,
      show: false,
      total: 1,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      loading: false,
      loadingFrom: false,
      list: [],
      classId: '',
      classes: [],
      log: null,
      babyList: []
    }
  },
  computed: {
    ...mapGetters(['curArea', 'user']),
    searchField () {
      const { classId } = this
      return [
        {
          key: 'name',
          label: '宝宝姓名'
        },
        {
          key: 'classId',
          label: '班级名称',
          type: 'select',
          initialValue: classId,
          fieldProps: {
            options: this.classes,
            props: { value: 'id', label: 'name' }
          },
          events: {
            change: val => this.classChange(val)
          }
        }
      ]
    },
    memorandumFrom () {
      config.memorandumFrom[1]['option'] = this.babyList
      return config.memorandumFrom
    }
  },
  async created () {
    await this.getClassList()
    await this.init()
  },
  methods: {
    getFile (arr) {
      let files = []
      if (arr[0] && arr[0]['file']) {
        files = arr[0]['file'].split(',')
      }
      return files
    },
    delChildrenMemorandum (id) {
      this.loading2()
      delChildrenMemorandum({ id }).then(res => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.init()
      }).finally(() => {
        this.log && this.log.close()
      })
    },
    delMemorandum (id) {
      this.loading2()
      delMemorandum({ id }).then(res => {
        this.show = false
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.init()
      }).finally(() => {
        this.log && this.log.close()
      })
    },
    getDetails (id) {
      this.loading2()
      details({ pageNum: 0, pageSize: 999, id }).then(res => {
        this.detail = res.content[0]
        this.show = true
      }).finally(() => {
        this.log && this.log.close()
      })
    },
    addMemorandum (item) {
      this.show = false
      this.detail = JSON.parse(JSON.stringify(item))
      this.detail['content'] = this.title === '编辑备忘录' ? this.detail['content'] : ''
      const files = this.detail['file'] ? this.detail['file'].split(',') : []
      const f = []
      for (let i = 0; i < files.length; i++) {
        f.push({ url: files[i], uid: files[i] })
      }
      this.detail['file'] = f
      config.memorandumFrom[0]['disabled'] = true
      config.memorandumFrom[1]['disabled'] = true
      this.drawer = true
    },
    init () {
      this.queryParams.pageNum = 1
      this.list = []
      this.getList()
    },
    // 获取备忘录列表
    getList () {
      const queryParams = JSON.parse(JSON.stringify(this.queryParams))
      queryParams.pageNum--
      queryParams['classesId'] = queryParams['classId']

      this.loading = true
      selChildrenMemorandumPage(queryParams).then(res => {
        this.loading = false
        this.list = res.content
        this.total = res.totalElements
      })
    },
    add () {
      this.title = '新增备忘录'
      config.memorandumFrom[0]['disabled'] = false
      config.memorandumFrom[1]['disabled'] = false
      this.detail = {}
      this.drawer = true
      this.$nextTick(() => {
        this.$refs.fromRef.formDate['classesId'] = this.classId
      })
    },
    selectChange (e) {
      const { type, value } = e
      if (type === 'classesId') {
        this.getbabyList(value)
        this.$set(this.$refs.fromRef.formDate, 'name', '')
      }
    },
    // 获取宝宝列表
    getbabyList (classId) {
      request({
        url: 'web/checkrecord/check_record_by_classId',
        method: 'post',
        params: { classId }
      }).then(res => {
        this.babyList = (res[0] ? (res[0].childrenList || []) : [])
        config.memorandumFrom[1]['option'] = (res[0] ? (res[0].childrenList || []) : [])
      })
    },
    beforeClose () {
      this.$refs.fromRef.resetFields()
      this.drawer = false
    },
    async submitForm (e) {
      const { user } = this
      const form = JSON.parse(JSON.stringify(e))
      const f = []
      if (form['file']) {
        for (let i = 0; i < form['file'].length; i++) {
          const file = form['file'][i]
          f.push(
            Object.prototype.toString.call(file) === '[object String]'
              ? file
              : file['url']
          )
        }
        form['file'] = f
      }
      if (form.name) {
        for (let i = 0; i < this.babyList.length; i++) {
          if (this.babyList[i]['childrenId'] === e.name) {
            form['chldrenId'] = e.name
            form['name'] = this.babyList[i]['childrenName']
          }
        }
      }
      if (e['file']) {
        form['file'] = e['file'] && e['file'].length > 0 ? e['file'].join() : ''
      }
      this.loadingFrom = true
      if (this.title === '编辑备忘录') {
        axios.post('/api/web/children/editMemorandum', { id: this.detail['id'], file: form['file'], content: form['content'], createUserId: user.id, createUserName: user.realName }, { headers: {
          'Content-Type': 'application/json'
        }}).then(res => {
          if (res.data.code === '000000') {
            this.init()
            this.$message({
              message: '编辑成功',
              type: 'success'
            })
            this.beforeClose()
            return
          }
          this.$message.error(res.data.msg)
        }).finally(() => {
          this.loadingFrom = false
        })
        return
      }
      if (this.detail['id']) {
        axios.post('/api/web/children/saveMemorandum', { relChildrenMemorandumId: this.detail['id'], file: form['file'], content: form['content'], createUserId: user.id, createUserName: user.realName }, { headers: {
          'Content-Type': 'application/json'
        }}).then(res => {
          if (res.data.code === '000000') {
            this.$message({
              message: '新增成功',
              type: 'success'
            })
            this.init()
            this.beforeClose()
            return
          }
          this.$message.error(res.data.msg)
        }).finally(() => {
          this.loadingFrom = false
        })
        return
      }
      axios.post('/api/web/children/saveChildrenMemorandum', { ...form, createUserId: user.id, createUserName: user.realName }, { headers: {
        'Content-Type': 'application/json'
      }}).then(res => {
        if (res.data.code === '000000') {
          this.$message({
            message: '新增成功',
            type: 'success'
          })
          this.init()
          this.beforeClose()
          return
        }
        this.$message.error(res.data.msg)
      }).finally(() => {
        this.loadingFrom = false
      })
    },
    getClassName (id) {
      let name = ''
      for (let i = 0; i < this.classes.length; i++) {
        if (this.classes[i]['id'] === id) {
          name = this.classes[i]['name']
        }
      }
      return name
    },
    // 加载动画
    loading2 (text = '请稍后...') {
      this.log = this.$loading({
        lock: true,
        text,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    /** 编辑按钮操作 */
    handleEdit () {
      this.title = '编辑宝宝'
      this.drawer = true
    },
    searchHandle (res) {
      this.queryParams.pageNum = 1
      this.list = []
      this.queryParams = { ...this.queryParams, ...res }
      this.getList()
    },
    // 获取班级列表
    getClassList () {
      const { curArea } = this
      getClassesByArea({ areaId: curArea.areaId, category: 1 }).then(res => {
        this.classes = res || []
        const id = this.classes[0] ? this.classes[0].id : ''
        config.memorandumFrom[0]['option'] = this.classes
        this.getbabyList(id)
      })
    },
    // 选择班级
    classChange (val) {
      this.classId = val
    }
  }
}
</script>

<style lang="scss" scope>
.drawer-box {
  padding: 16px;
  background: #FAFAFD;
  border-radius: 4px;
  border: 1px solid #EBEBEE;
}

.drawer-top {
  display: flex;
  justify-content: space-between;
  align-items: center;

  div {
    font-family: Source Han Sans SC, Source Han Sans SC;
    font-weight: 500;
    text-align: left;
    font-style: normal;
    text-transform: none;
    font-size: 18px;
  }
}

.baby-box .pagination-container {
  margin-top: 0px;
}

.baby-table {
  width: 100%;
  height: calc(100% - 80px);
}

.baby-box {
  margin-top: 16px;
  background-color: #FFFFFF;
  border-radius: 8px;
  padding: 24px;
}

.baby-box {
  th.is-leaf {
    height: 66px;
  }

  th {
    color: #000;
    font-size: 17px;
    background: #FAFAFA;
    font-family: PingFang SC;
    font-weight: bold;
  }

  td {
    padding: 20px 0
  }
}

.quesheng {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  height: 100%;

  span {
    font-family: Source Han Sans SC, Source Han Sans SC;
    font-weight: 400;
    font-size: 16px;
    color: #333333;
    font-style: normal;
    text-transform: none;
    margin-top: 32px;
  }
}

.searchBox .el-form-item {
  margin-bottom: 0 !important;
}

.baby-box .el-table--border {
  border: 0;
}

.searchBox {
  background: #FFFFFF;
  border-radius: 8px;
  padding: 16px 20px;
}

.hint {
  margin-top: 10px;
}

.weekend-bg {
  background: #7d7d7f;
  width: 100%;
  height: 100%;
}

.el-table {
  .cell {
    padding: 0;
  }
}

.el-table {
  th {
    .cell {
      padding: 0;
    }
  }

}

.memorandum-box {
  padding: 16px;
  background-color: #EBEBEE;
  border-radius: 4px;
  width: 632px;

  &-item {
    width: 600px;
    word-break: break-all;
    font-family: Source Han Sans SC, Source Han Sans SC;
    font-weight: 400;
    font-size: 14px;
    color: #333333;
    font-style: normal;
    text-transform: none;
    margin-bottom: 16px;
    border: 1px solid #EBEBEE;
  }

  &-item:last-child {
    margin-bottom: 0 !important;
  }
}

.memorandum-title {
  font-weight: bold;
  color: black;
  margin: 16px 0;
}
</style>
